//
// Created by EDY on 2025/10/11.
//

#ifndef EPOLL_MICROGRID_CONNECTIONMANGER_H
#define EPOLL_MICROGRID_CONNECTIONMANGER_H

#include <stdint.h>
#include <pthread.h>
#include <stdatomic.h>
#include <time.h>
#include "../../thridParty/uthash/uthash.h"
#include "../deviceManger/device.h"

#define MAX_CONNECTIONS 1000    //最大连接数
#define CONN_TIMEOUT 300        //5分钟超时
#define HEARTBEAT_INTERVAL 30   //心跳间隔

//连接状态枚举
typedef enum {
    CONN_STATE_IDLE = 0,    //空闲
    CONN_STATE_CONNECTED,   //已连接但未绑定
    CONN_STATE_BOUND,       //已绑定
    CONN_STATE_TIMEOUT,     //超时
    CONN_STATE_ERROR        //错误状态
}ConnectionState;

//连接统计信息
typedef struct {
    uint64_t bytes_received;
    uint64_t bytes_sent;
    uint64_t packets_received;
    uint64_t packets_sent;
    uint32_t error_count;
    time_t first_connect_times;
    time_t las_heartbeat;
}ConnectionStats;

typedef struct {
    int sock_fd;                        //sock_fd作为哈希key
    int conn_id;                        //连接唯一id
    DeviceContext *devcie_ctx;          //设备上下文
    ConnectionStats stats;              //统计信息
    ConnectionState state;              //设备状态
    time_t last_active;                 //最后活跃时间
    time_t connect_time;                //连接建立时间
    pthread_mutex_t conn_lock;          //锁
    uint8_t in_use;                     //使用标记

    UT_hash_handle hh;                  //uthash句柄，必须命名为hh
}Connection;

//连接ID到连接的映射（用于通过conn_id查找）
typedef struct ConnectionIdMap {
    int conn_id;                        //连接ID作为key
    Connection *connection;
    UT_hash_handle hh;
}ConnectionIdMap;



typedef struct {
    Connection *connections_by_fd;              //按socket_fd索引的连接哈希表
    ConnectionIdMap *connections_by_id;         //按conn_id索引的连接哈希表
    pthread_rwlock_t hash_lock;                 //哈希读写锁

    //连接id生成器
    atomic_int next_conn_id;

    struct {
        uint32_t total_connections;
        uint32_t active_connections;
        uint32_t max_concurrent;
        uint64_t total_bytes_transferred;
        time_t start_time;
    }global_stats;

}ConnectionManger;

int connection_manager_init(void);
void connection_manager_destroy(void);
Connection* connection_acquire(int sock_fd);
int connection_release(Connection *conn);
int connection_bind_device(Connection *conn,Device *device);
int conection_unbind_device(Connection *conn);
Connection *connection_find_by_fd(int sock_fd);
Connection *connection_find_by_id(int conn_id);
int connection_update_stats(Connection *conn,size_t bytes_in , size_t bytes_out);
int connection_check_timeout(void);
int connection_send_heartbeat(Connection *conn);
void Connection_print_stats(void);
ConnectionState connection_get_state(Connection *conn);
int connection_set_state(Connection *conn,ConnectionState new_state);

// 遍历所有连接的回调函数类型
typedef int (*connection_callback_t)(Connection *conn, void *user_data);
int connection_foreach(connection_callback_t callback, void *user_data);

#endif //EPOLL_MICROGRID_CONNECTIONMANGER_H